package com.rongshu.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.rongshu.R;
import com.rongshu.eventbus.OpenAudioPlayUI;
import com.rongshu.view.mediaPlayer.bean.AudiobookDetailsResponse;
import com.rongshu.view.mediaPlayer.bean.PlayEvent;
import com.rongshu.view.mediaPlayer.emnu.MediaState;
import com.rongshu.view.mediaPlayer.emnu.PlayAction;
import com.rongshu.view.mediaPlayer.manager.PlayerManager;
import com.utils.LogUtil;

import org.greenrobot.eventbus.EventBus;

import static android.content.Context.WINDOW_SERVICE;

/**
 * created by zhengweis on 2019/4/29.
 * description：
 */
public class AudiobookFloatWindow implements View.OnClickListener {
    private Context context;
    private WindowManager mWindowManager;
    private WindowManager.LayoutParams mLayoutParams;
    private View mView;
    private int mY;
    //可移动的范围
    private int rangeTopY, rangeBottomY;
    private boolean isAdd = false;
    //悬浮窗是否在显示
    private boolean isShow;
    //悬浮窗是否展开
    private boolean isExpand = true;
    private ImageView mediaCover, playMedia, closeMedia, beforMedia, nextMedia;
    private RelativeLayout coverLayout;
    private RoundProgress progress;
    private LinearLayout mediaOption;
    private CloseMiniWindowListener closeMiniWindowListener;
    private Handler handler;
    //音频总时长
    private int duration;

    public AudiobookFloatWindow(Context context) {
        this.context = context;
        mWindowManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
        mLayoutParams = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            mLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        mLayoutParams.format = PixelFormat.RGBA_8888;
        mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
//                | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
        mView = View.inflate(context, R.layout.layout_media_play_backstage, null);
        mLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        mLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        initViews();
        initTouchEvent();
        handler = new Handler();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initViews() {
        mediaCover = mView.findViewById(R.id.book_cover);
        mediaOption = mView.findViewById(R.id.media_option);
        playMedia = mView.findViewById(R.id.play_media);
        closeMedia = mView.findViewById(R.id.close_media);
        coverLayout = mView.findViewById(R.id.cover_layout);
        progress = mView.findViewById(R.id.audio_progress);
        beforMedia = mView.findViewById(R.id.before_media);
        nextMedia = mView.findViewById(R.id.next_media);
        coverLayout.setOnClickListener(this);
        playMedia.setOnClickListener(this);
        closeMedia.setOnClickListener(this);
        beforMedia.setOnClickListener(this);
        nextMedia.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.cover_layout) {
            if (isExpand) {
                AudiobookDetailsResponse.ResponseBean nowPlaying = PlayerManager.getPlayer().getNowPlaying();
                if (nowPlaying != null) {
                    OpenAudioPlayUI audioPlayUI = new OpenAudioPlayUI();
                    audioPlayUI.setId(nowPlaying.getId());
                    EventBus.getDefault().post(audioPlayUI);
                }
            } else {
                updateViewVisible(true);
            }
        } else if (id == R.id.play_media) {
            if (PlayerManager.getPlayer().getDuration() == 0 ||
                    PlayerManager.getPlayer().getMediaState() == MediaState.COMPLETED) {
                return;
            }
            PlayEvent playEvent = new PlayEvent();
            if (PlayerManager.getPlayer().isPlaying()) {
                playEvent.setAction(PlayAction.PAUST);
                EventBus.getDefault().post(playEvent);
                Glide.with(context).load(R.drawable.mini_pop_pause_icon).into(playMedia);
            } else {
                playEvent.setAction(PlayAction.PLAY);
                EventBus.getDefault().post(playEvent);
                Glide.with(context).load(R.drawable.mini_pop_play_icon).into(playMedia);
            }
        } else if (id == R.id.close_media) {
            PlayEvent playEvent = new PlayEvent();
            playEvent.setAction(PlayAction.STOP);
            EventBus.getDefault().post(playEvent);
            if (closeMiniWindowListener != null) {
                closeMiniWindowListener.close();
            }
        }
    }

    private void initTouchEvent() {
        mView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        handler.removeCallbacks(runnable);
                        LogUtil.i("ACTION_DOWN", "ACTION_DOWN======" + mY);
                        break;
                    case MotionEvent.ACTION_MOVE:
                        int nowY = (int) event.getRawY();
                        LogUtil.i("ACTION_MOVE", "ACTION_MOVE===nowY===" + nowY);
                        LogUtil.i("ACTION_MOVE", "ACTION_MOVE===mY===" + mY);
                        int movedY = mY - nowY;
                        mY = nowY;
                        mLayoutParams.x = 30;
                        mLayoutParams.y = mLayoutParams.y + movedY;
                        LogUtil.i("ACTION_MOVE", "ACTION_MOVE===mLayoutParams.y===" + mLayoutParams.y);
                        if (mLayoutParams.y > rangeTopY) {
                            mLayoutParams.y = rangeTopY;
                            mY = rangeBottomY;
                            LogUtil.i("ACTION_MOVE", "ACTION_MOVE===+++++++++++++");
                        }
                        if (mLayoutParams.y < rangeBottomY) {
                            mLayoutParams.y = rangeBottomY;
                            mY = rangeTopY;
                            LogUtil.i("ACTION_MOVE", "ACTION_MOVE===*************");
                        }
                        mWindowManager.updateViewLayout(mView, mLayoutParams);
                        break;
                    case MotionEvent.ACTION_UP:
                        if (isExpand) {
                            handler.postDelayed(runnable, 4000);
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });

    }

    public interface CloseMiniWindowListener {
        void close();
    }

    public void setCloseListener(CloseMiniWindowListener closeMiniWindowListener) {
        this.closeMiniWindowListener = closeMiniWindowListener;
    }

    /**
     * 设置上下拖动的范围
     *
     * @param rangeTopY
     * @param rangeBottomY
     */
    public void setMoreRange(int rangeTopY, int rangeBottomY) {
        this.rangeTopY = rangeTopY;
        this.rangeBottomY = rangeBottomY;
    }

    /**
     * 设置显示的初始位置
     *
     * @param gravity
     * @param xOffset
     * @param yOffset
     */
    public void setGravity(int gravity, int xOffset, int yOffset) {
        mLayoutParams.gravity = gravity;
        mLayoutParams.x = xOffset;
        mLayoutParams.y = yOffset;
        ViewTreeObserver topMenuViewTreeObserver = mView.getViewTreeObserver();
        topMenuViewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                int height = context.getResources().getDimensionPixelOffset(R.dimen.dd_dimen_80px);
                int[] position = new int[2];
                mView.getLocationOnScreen(position);
                mY = position[1] + height / 2;
                return true;
            }
        });
    }

    /**
     * 显示
     */
    public void show() {
        if (!isAdd) {
            mWindowManager.addView(mView, mLayoutParams);
            isAdd = true;
            if (isExpand) {
                handler.postDelayed(runnable, 4000);
            }
        } else if (!isShow) {
            mView.setVisibility(View.VISIBLE);
        }
        isShow = true;
    }

    /**
     * 展开/折叠 mini窗
     */
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            updateViewVisible(false);
        }
    };

    /**
     * 更新 进度条
     */
    Runnable progressRunnable = new Runnable() {
        @Override
        public void run() {
            if (PlayerManager.getPlayer().getMediaState() != MediaState.COMPLETED) {
                int mediaCurrentPositon = PlayerManager.getPlayer().getCurrentPosition();
                progress.setProgress(mediaCurrentPositon / 1000);
                handler.postDelayed(progressRunnable, 1000);
            } else {
                progress.setProgress(duration <= 0 ? 0 : duration);
                handler.removeCallbacks(progressRunnable);
            }
        }
    };

    public void updateViewVisible(boolean isExpand) {
        this.isExpand = isExpand;
        if (isExpand) {
            duration = PlayerManager.getPlayer().getDuration();
            progress.setMax(duration / 1000);
            if (PlayerManager.getPlayer().isPlaying()) {
                Glide.with(context).load(R.drawable.mini_pop_play_icon).into(playMedia);
            } else {
                Glide.with(context).load(R.drawable.mini_pop_pause_icon).into(playMedia);
            }
            //更新 进度条
            if (PlayerManager.getPlayer().getMediaState() != MediaState.COMPLETED) {
                int mediaCurrentPositon = PlayerManager.getPlayer().getCurrentPosition();
                progress.setProgress(mediaCurrentPositon / 1000);
            } else {
                progress.setProgress(duration <= 0 ? 0 : duration);
            }
            mediaOption.setVisibility(View.VISIBLE);
            handler.removeCallbacks(runnable);
            handler.removeCallbacks(progressRunnable);
            handler.postDelayed(runnable, 4000);
            handler.postDelayed(progressRunnable, 1000);
        } else {
            mediaOption.setVisibility(View.GONE);
            handler.removeCallbacks(runnable);
        }
    }

    /**
     * 消失
     */
    public void dimiss() {
        if (isShow) {
            mView.setVisibility(View.INVISIBLE);
        }
        isShow = false;
    }

    /**
     * 清空
     */
    public void clear() {
        PlayEvent playEvent = new PlayEvent();
        playEvent.setAction(PlayAction.STOP);
        EventBus.getDefault().post(playEvent);
        handler.removeCallbacksAndMessages(null);
        mWindowManager.removeView(mView);
        mWindowManager = null;
    }

    public boolean isExpand() {
        return isExpand;
    }

    public void updateCoverImg(String url) {
        Glide.with(context).load(url).into(mediaCover);
    }
}
